# 导包
import smtplib, time, os
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
class SendEmail:

    def __init__(self):
        # 第一步：配置邮箱属性
        # 发送邮箱
        self.sender = '825622958@qq.com'
        # 接收邮箱
        self.receiver = '825622958@qq.com'
        # 发送邮件主题
        t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.subject = '自动化测试结果_' + t
        # 发送邮箱服务器
        self.smtpserver = 'smtp.qq.com'
        # 发送邮箱用户/密码
        self.username = '825622958@qq.com'
        self.password = 'dfgtfujqrceqbbgd'

    def __config(self, file):
        # 第二步：准备附件，增加附件，组装邮件内容和标题
        # 读取html文件内容
        with open(file, 'rb') as f:
            mail_body = f.read()
            # 组装邮件内容和标题
            self.msg = MIMEMultipart()
            # 添加附件内容
            att = MIMEText(mail_body, 'plain', 'utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att["Content-Disposition"] = 'attachment; filename=report.html'
            self.msg.attach(att)
            # 添加邮件的文本内容
            content = '自动化测试报告详情，请查收附件'
            self.msg.attach(MIMEText(content, 'plain', 'utf-8'))
            self.msg['Subject'] = Header(self.subject, 'utf-8')
            self.msg['From'] = self.sender
            self.msg['To'] = self.receiver

    def send(self, file):
        self.__config(file)
        try:
            # 1--实例化smtp类
            smtp = smtplib.SMTP()
            # 2--连接stmp服务器
            smtp.connect(self.smtpserver)
            # 3--登录邮箱
            smtp.login(self.username, self.password)
            # 4--设置发件人，收件人，邮件内容
            smtp.sendmail(self.sender, self.receiver, self.msg.as_string())
        except Exception as msg:
            print("邮件发送失败！%s" % msg)
        else:
            print("邮件发送成功！")
        finally:
            smtp.quit()


if __name__ == '__main__':
    ce = SendEmail()
    path1 = os.path.dirname(os.path.dirname(__file__)) + r"/testReport/2022_06_22_22_03_20report.html"
    ce.send(path1)
